package com.hbxy.favorite.logger;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

//申明是个切面
@Aspect
//申明是个spring管理的bean
@Component
@Order(1)
public class AspectLog {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    private Gson gson = new Gson();

    //申明一个切点 里面是 execution表达式
    @Pointcut("execution(public * com.hbxy.favorite.controller.*.*(..))")
    private void controllerAspect() {
    }


    //请求method前打印内容
    @Before(value = "controllerAspect()")
    public void methodBefore(JoinPoint joinPoint) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        //打印请求内容
        log.info("==================================================REQUEST============================================");
        log.info("Date      :" + new Date());
        log.info("Token     :" + request.getHeader("token"));
        log.info("Url       :" + request.getRequestURL().toString());
        log.info("Method    :" + request.getMethod());
        log.info("Signature :" + joinPoint.getSignature());
        log.info("Args      :" + JSON.toJSON(joinPoint.getArgs()));
        log.info("==================================================REQUEST============================================");
    }


    //在方法执行完结后打印返回内容
    @AfterReturning(returning = "o", pointcut = "controllerAspect()")
    public void methodAfterReturing(Object o) {
        log.info("--------------------------------------------------RESPONSE-------------------------------------------");
        log.info("Response  :" + gson.toJson(o));
        log.info("--------------------------------------------------RESPONSE-------------------------------------------");
    }
}
